import pygame
import random
import os
import cfg
'''辅助函数模块'''

def get_random_grid_position(cfg):
    """生成网格内的随机位置 [col, row]"""
    x_grid = random.randint(0, cfg.GRID_WIDTH - 1)
    y_grid = random.randint(0, cfg.GRID_HEIGHT - 1)
    return [x_grid, y_grid]

def grid_to_pixel(grid_pos, cfg):
    """将网格坐标转换为像素坐标 (左上角)"""
    # Ensure grid_pos is valid before calculation
    if grid_pos is None or len(grid_pos) != 2:
        print(f"Error: Invalid grid_pos {grid_pos} in grid_to_pixel")
        return [0, 0] # Or raise an error
    return [grid_pos[0] * cfg.GRID_SIZE, grid_pos[1] * cfg.GRID_SIZE]

def draw_grid_cell(screen, grid_pos, color, cfg):
    """在指定网格位置绘制一个方块"""
    pixel_pos = grid_to_pixel(grid_pos, cfg)
    pygame.draw.rect(screen, color, pygame.Rect(pixel_pos[0], pixel_pos[1], cfg.GRID_SIZE, cfg.GRID_SIZE))

def drawGameGrid(cfg, screen):
    """绘制游戏区域的网格线"""
    for x in range(0, cfg.WIDTH + 1, cfg.GRID_SIZE): # Draw lines including right/bottom edge
        pygame.draw.line(screen, cfg.GRID_COLOR, (x, 0), (x, cfg.HEIGHT))
    for y in range(0, cfg.HEIGHT + 1, cfg.GRID_SIZE):
        pygame.draw.line(screen, cfg.GRID_COLOR, (0, y), (cfg.WIDTH, y))

def display_score(screen, score, level, target_score, cfg):
    """显示分数和关卡信息 (使用指定字体)"""
    y_pos = 10
    x_pos = 10

    # Level/Mode Text (using Main Font)
    if level > 0: # 关卡模式
        level_text = f"关卡: {level}/{cfg.MAX_LEVEL}"
        if target_score > 0:
             level_text += f"  目标: "
             target_num_text = str(target_score)
        else:
             target_num_text = None # No target number if target_score is 0
    else: # 传统模式
        level_text = "模式: 传统模式"
        target_num_text = None

    level_surf = cfg.FONT_MAIN_MEDIUM.render(level_text, True, cfg.WHITE)
    level_rect = level_surf.get_rect(topleft=(x_pos, y_pos))
    screen.blit(level_surf, level_rect)
    current_x = level_rect.right

    # Target Score Number (using Number Font, if applicable)
    if target_num_text:
        target_num_surf = cfg.FONT_SCORE.render(target_num_text, True, cfg.WHITE)
        target_num_rect = target_num_surf.get_rect(midleft=(current_x, level_rect.centery))
        screen.blit(target_num_surf, target_num_rect)
        current_x = target_num_rect.right + 20 # Add spacing after target score
    else:
        current_x += 20 # Add spacing anyway if no target score

    # Score Text (using Main Font)
    score_label_text = "分数: "
    score_label_surf = cfg.FONT_MAIN_MEDIUM.render(score_label_text, True, cfg.WHITE)
    # Position score label relative to level/target text, vertically aligned
    score_label_rect = score_label_surf.get_rect(midleft=(current_x, level_rect.centery))
    screen.blit(score_label_surf, score_label_rect)
    current_x = score_label_rect.right

    # Score Number (using Number Font)
    score_num_text = str(score)
    score_num_surf = cfg.FONT_SCORE.render(score_num_text, True, cfg.WHITE)
    score_num_rect = score_num_surf.get_rect(midleft=(current_x, level_rect.centery))
    screen.blit(score_num_surf, score_num_rect)

def display_centered_message(screen, message, color, size, cfg, duration=None):
    """
    显示消息到屏幕中央 (使用主字体).
    If duration is None, it just draws; otherwise, it draws, updates, and waits.
    """
    if size == "large":
        font = cfg.FONT_MAIN_LARGE
    elif size == "xlarge":
        font = cfg.FONT_MAIN_XLARGE
    else: # medium or small
        font = cfg.FONT_MAIN_MEDIUM

    text_surface = font.render(message, True, color)
    text_rect = text_surface.get_rect(center=(cfg.WIDTH // 2, cfg.HEIGHT // 2))

    # Optional: Add semi-transparent background for better readability
    bg_rect = text_rect.inflate(40, 20)
    bg_surface = pygame.Surface(bg_rect.size, pygame.SRCALPHA)
    bg_surface.fill((0, 0, 0, 180)) # Semi-transparent black
    screen.blit(bg_surface, bg_rect.topleft)

    screen.blit(text_surface, text_rect)

    if duration is not None and duration > 0:
        pygame.display.update(bg_rect) # Update only the message area
        try:
             pygame.time.wait(int(duration * 1000)) # Wait if duration is specified
        except OverflowError: # Handle potential large duration values
             print("Warning: display_centered_message duration too large.")
             pygame.time.wait(5000) # Wait max 5 seconds

def load_achievements():
    """加载成就排行榜"""
    if not os.path.exists(cfg.ACHIEVEMENTS_FILE):
        return {}
    with open(cfg.ACHIEVEMENTS_FILE, 'r') as file:
        lines = file.readlines()
        achievements = {}
        for line in lines:
            mode, score = line.strip().split(',')
            achievements[mode] = int(score)
        return achievements

def save_achievements(achievements):
    """保存成就排行榜"""
    with open(cfg.ACHIEVEMENTS_FILE, 'w') as file:
        for mode, score in achievements.items():
            file.write(f"{mode},{score}\n")
